#include <controller/TLSController.h>
#include <localview/LocalView.h>
#include <localview/Network.h>
#include <controller/TimeIncrementCalculationStrategy.h>
#include <evolutive/TimeIncrementEvolutiveStrategy.h>
#include <controller/Case.h>
#include <log.h>

TLSController::TLSController(std::string tlsId, localview::Network* network) {

	mLocalView = new localview::LocalView(tlsId, network);

	rsi::log("TLSController", __FILE__, __LINE__, "Created a new controller %s", tlsId.c_str());
}

TLSController::~TLSController() {
}

void TLSController::startPhaseIncrementCalc(int phaseId, int timestep) {
	rsi::log("controller", __FILE__, __LINE__, "Starting Increment calc to tls: %s, phase: %d", mLocalView->getTLSId().c_str(), phaseId);

	TimeIncrementCalculationStrategy* strategy = new TimeIncrementEvolutiveStrategy();

	registerBackgroundCalcTask(strategy, phaseId);

	strategy->start(mLocalView, phaseId, timestep);
}

int TLSController::getPhaseIncrement(int phaseId) {

	if(mActiveCalc.find(phaseId) == mActiveCalc.end()) {
		return 0;
	}

	TimeIncrementCalculationStrategy* strategy = mActiveCalc[phaseId];
	strategy->stop();

	Case* c = strategy->getResult();

	int extension = c->getLocalGreenExtension();

	unregisterBackgroundCalcTask(phaseId);

	return extension;
}

void TLSController::registerBackgroundCalcTask(TimeIncrementCalculationStrategy* tics, int phaseId) {
	mActiveCalc[phaseId] = tics;
}

TimeIncrementCalculationStrategy* TLSController::unregisterBackgroundCalcTask(int phaseId) {
	TimeIncrementCalculationStrategy* strategy = mActiveCalc[phaseId];
	mActiveCalc.erase(phaseId);
	delete strategy;

	return 0;
}

